package com.hgl.bi.web.config;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @program: BI
 * @description: deepseek客户端配置
 * @author: hgl
 * @create: 2025-02-15 22:38
 */
@Slf4j
@Data
@Configuration
public class DeepSeekClient {

    @Value("${ai.client.baseUrl}") // 按名称自动映射yml中的字段值
    private String baseUrl;

    @Value("${ai.client.model}") // 按名称自动映射yml中的字段值
    private String model;

    @Value("${ai.client.apiKey}") // 按名称自动映射yml中的字段值
    private String apiKey;

    private final OkHttpClient client = new OkHttpClient().newBuilder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(120, TimeUnit.SECONDS)
            .build();

    public String callDeepSeekApi(String prompt, String csvData) throws IOException {
        // 构建消息体
        JSONArray messages = new JSONArray();
        messages.add(new JSONObject().putOnce("role", "system").putOnce("content", prompt));
        messages.add(new JSONObject().putOnce("role", "user").putOnce("content", csvData));
        // 构建请求
        Request request = new Request.Builder()
                .url(baseUrl)
                .addHeader("Authorization", "Bearer " + apiKey)
                .addHeader("Content-Type", "application/json")
                .post(RequestBody.create(
                        new JSONObject()
                                .putOnce("model", model)
                                .putOnce("messages", messages)
                                .putOnce("stream", false) // 流式处理
                                .putOnce("temperature", 0.7)
                                .putOnce("max_tokens", 1000)
                                .toString(),
                        MediaType.parse("application/json; charset=utf-8")
                ))
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("原始响应: " + response);
            }
            // 获取响应体
            String responseBody = response.body().string();
            log.info("响应体: {}", responseBody);
            // 使用Hutool 解析响应
            JSONObject root = new JSONObject(responseBody);
            // 非空判断
            JSONArray choices = root.getJSONArray("choices");
            if (choices == null || choices.isEmpty()) {
                throw new IOException("响应缺乏必要字段");
            }
            // 提取content字段
            String content = root.getJSONArray("choices")
                    .getJSONObject(0)
                    .getJSONObject("message")
                    .getStr("content");
            // 提取有效JSON
            return content;
        }
    }

    /**
     * 从代码块提取有效JSON
     *
     * @param content 代码块内容
     * @return String
     */
    public String extractContent(String content) {
        // 去除代码块标记和换行
        String jsonObject = content.replaceAll("(?i)^[\\s【]*", "")
                .replaceAll("[\\s【]*$", "");
        try {
            // 二次验证JSON结构
            new JSONObject(jsonObject);
            return jsonObject;
        } catch (Exception e) {
            log.error("JSON解析失败: {}", jsonObject);
            // 如果JSON结构不正确，则返回空字符串
            return "";
        }
    }
}
